package com.loe.mvp.util.selecter;

import android.view.View;

import java.util.ArrayList;

/**
 * 多选器
 * Created by zls on 2017/1/16.
 */
public class Checker implements View.OnClickListener
{
    private ArrayList<SelectItem> list;
    private ArrayList<Boolean> checkList;

    private OnCheckListener onCheckListener;

    public Checker()
    {
        list = new ArrayList<>();
        checkList = new ArrayList<>();
    }

    /**
     * 添加元素
     */
    public void add(SelectItem selectItem)
    {
        list.add(selectItem);
        checkList.add(false);
        selectItem.view.setOnClickListener(this);
    }

    /**
     * 选择
     */
    public void check(View view)
    {
        for (int i = 0; i < list.size(); i++)
        {
            SelectItem item = list.get(i);

            if (view.equals(item.view))
            {
                checkList.set(i, !checkList.get(i));
                if (checkList.get(i))
                {
                    item.selectIn();
                }
                else
                {
                    item.selectOut();
                }
                if (onCheckListener != null)
                {
                    onCheckListener.onCheck(i, checkList.get(i));
                }
            }
        }
    }

    /**
     * 选择全部
     */
    public void checkAll(boolean isSelect)
    {
        for (int i = 0; i < list.size(); i++)
        {
            SelectItem item = list.get(i);
            checkList.set(i, isSelect);
            if (isSelect)
            {
                item.selectIn();
            }
            else
            {
                item.selectOut();
            }
        }
    }

    public ArrayList<Integer> getData()
    {
        ArrayList<Integer> aList = new ArrayList<>();
        for (int i = 0; i < checkList.size(); i++)
        {
            if(checkList.get(i)) aList.add(i);
        }
        return aList;
    }

    public String getDataString(String split)
    {
        StringBuilder sb = new StringBuilder();
        String c = "";
        for (int i = 0; i < checkList.size(); i++)
        {
            if(checkList.get(i)) sb.append(c + i);
            c = split;
        }
        return sb.toString();
    }

    public String getDataString()
    {
        return getDataString(",");
    }

    @Override
    public void onClick(View v)
    {
        check(v);
    }

    /**
     * 添加选择监听器
     */
    public void setOnCheckListener(OnCheckListener onCheckListener)
    {
        this.onCheckListener = onCheckListener;
    }

    /**
     * 选择监听器
     */
    public interface OnCheckListener
    {
        void onCheck(int index, boolean isCheck);
    }
}
